#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
发布脚本
"""

import os
import sys
import subprocess
import shutil
from datetime import datetime

def run_command(cmd, check=True):
    """运行命令"""
    print(f"运行命令: {cmd}")
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    if check and result.returncode != 0:
        print(f"命令失败: {cmd}")
        print(f"错误输出: {result.stderr}")
        sys.exit(1)
    return result

def clean_build():
    """清理构建文件"""
    print("清理构建文件...")
    dirs_to_clean = ['build', 'dist', '*.egg-info']
    for pattern in dirs_to_clean:
        if os.path.exists(pattern):
            if os.path.isdir(pattern):
                shutil.rmtree(pattern)
            else:
                os.remove(pattern)

def build_package():
    """构建包"""
    print("构建包...")
    run_command("python -m build")

def check_package():
    """检查包"""
    print("检查包...")
    run_command("twine check dist/*")

def upload_to_pypi():
    """上传到PyPI"""
    print("上传到PyPI...")
    run_command("twine upload dist/*")

def create_git_tag(version):
    """创建Git标签"""
    print(f"创建Git标签: v{version}")
    run_command(f"git tag -a v{version} -m 'Release version {version}'")
    run_command("git push origin --tags")

def main():
    """主函数"""
    if len(sys.argv) < 2:
        print("用法: python scripts/release.py <version>")
        print("示例: python scripts/release.py 1.0.0")
        sys.exit(1)
    
    version = sys.argv[1]
    
    print(f"开始发布版本 {version}...")
    
    # 检查工作目录是否干净
    result = run_command("git status --porcelain", check=False)
    if result.stdout.strip():
        print("工作目录不干净，请先提交所有更改")
        sys.exit(1)
    
    # 清理构建文件
    clean_build()
    
    # 构建包
    build_package()
    
    # 检查包
    check_package()
    
    # 询问是否上传
    upload = input("是否上传到PyPI? (y/n): ").strip().lower()
    if upload in ['y', 'yes']:
        upload_to_pypi()
    
    # 创建Git标签
    create_git_tag(version)
    
    print(f"版本 {version} 发布完成!")

if __name__ == "__main__":
    main()
